using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Wixa.Api.Options;
using Wixa.IBusiness.Base_Manage;
using Wixa.Models.Base_Manage;
using Wixa.Models.DTO;

namespace Wixa.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        private readonly JwtOptions _jwtOptions;
        readonly IBase_UserBusiness _userBus;

        public HomeController(IOptions<JwtOptions> jwtOptions, IBase_UserBusiness userBus)
        {
            _jwtOptions = jwtOptions.Value;
            _userBus = userBus;
        }

        [HttpGet]
        [AllowAnonymous]
        public string GetToken()
        {
            var claims = new[]
            {
                new Claim("userId","")
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(
                string.Empty,
                string.Empty,
                claims,
                expires: DateTime.Now.AddHours(_jwtOptions.AccessExpireHours),
                signingCredentials: credentials);

            var tokenStr = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return tokenStr;
        }

        [HttpGet]
        public List<Base_User> GetUsers()
        {
            return _userBus.GetDataList();
        }

        [HttpPost]
        [AllowAnonymous]
        public void Build(BuildInputDTO input)
        {
            _userBus.Build(input);
        }
    }
}